package com.young.commom.httpclient.okhttp;

import com.young.commom.httpclient.HttpClientConfiguration;
import com.young.common.expression.dns.NamingResolver;
import okhttp3.ConnectionPool;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.OkHttpClient.Builder;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @description：
 * @author: yangyahui01
 * @date: 11/29/24 1:01 PM
 */
public final class OkHttpClientBuilder {
    public OkHttpClientBuilder() {
    }

    public static OkHttpClient build(HttpClientConfiguration configuration) {
        return build(configuration, (List)null);
    }

    public static OkHttpClient build(HttpClientConfiguration configuration, List<Interceptor> interceptors) {
        OkHttpClient.Builder builder = new Builder();
        builder.connectTimeout(configuration.getConnectionTimeout(), TimeUnit.MILLISECONDS);
        ConnectionPool connectionPool = new ConnectionPool(3, configuration.getKeepAliveTime(), TimeUnit.MILLISECONDS);
        builder.connectionPool(connectionPool);
        builder.readTimeout(configuration.getSocketTimeout(), TimeUnit.MILLISECONDS);
        builder.retryOnConnectionFailure(configuration.getRetryOnFailure());
        builder.writeTimeout(configuration.getSocketTimeout(), TimeUnit.MILLISECONDS);
        if (interceptors != null) {
            Iterator var4 = interceptors.iterator();

            while(var4.hasNext()) {
                Interceptor interceptor = (Interceptor)var4.next();
                builder.addInterceptor(interceptor);
            }
        }

        if (configuration.isDnsResolverEnabled()) {
            NamingResolver namingResolver = configuration.getNamingResolver();
            if (namingResolver != null) {
                builder.dns((hostname) -> {
                    return Arrays.asList(namingResolver.resolve(hostname));
                });
            }
        }

        return builder.build();
    }

    public static OkHttpClient build() {
        HttpClientConfiguration configuration = HttpClientConfiguration.common();
        return build(configuration);
    }
}
